package com.hmkj.web.config;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.core.constant.SessionId;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Aspect   //定义一个切面
@Configuration
public class ControllerAspect {
    // 定义切点Pointcut
    @Pointcut("execution(* com.hmkj.web.controller..*Controller..*(..))")
    public void excudeResult() {
    }

    @Around("excudeResult()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
//        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
//        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
//        HttpServletRequest request = sra.getRequest();

        Object val = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getAttribute(SessionId.COOKIE_SESSIONID);
        String sid = val == null ? null : val.toString();

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        if (result instanceof ResultEntity && StrUtil.isNotBlank(sid)) {
            ((ResultEntity) result).setHid(sid);
        }

        return result;
    }
}
